<template>
  <div>
    <el-form ref="formRef" :model="form" label-width="auto">
      <el-form-item label="名称：">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="B站地址：">
        <el-input v-model="form.bsite"></el-input>
      </el-form-item>
      <el-form-item label="技术网址：">
        <el-input v-model="form.techSite"></el-input>
      </el-form-item>
      <el-form-item label="作者：">
        <el-input v-model="form.writer"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即创建</el-button>
        <el-button @click="back">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { ref, reactive, toRefs, onBeforeMount } from "vue"
import { addKnow, updateKnow } from "../../api/knowledge"
import { useRouter, useRoute } from "vue-router"
import { toast } from "../../utils/toast"

interface message {
  msg: string
  type: string
  duration: Number
}
export default {
  setup() {
    const formRef = ref(null)
    const formData = reactive({
      form: {
        id: "",
        name: "",
        bsite: "",
        techSite: "",
        writer: ""
      }
    })
    const iRouter = useRouter()
    const route = useRoute()

    onBeforeMount(() => {
      // console.log(route.query.id, "route参数");
      if (route.query.id && route.query.id !== "") {
        formData.form.id = route.query.id as string
        // 修改面包屑显示文字
        route.meta.title = "修改知识"
        console.log(route.query, "route.query")
        const params: any = route.query.params
        formData.form = { ...formData.form, ...JSON.parse(params)}
      }
    })

    const onSubmit = () => {
      console.log(formData.form, "submit!")
      if (formData.form.id !== "") {
        updateKnow(formData.form).then((data) => {
          // 原因：axios 类型错误
          toast(data.msg)
          console.log(data, "修改成功")
          if (data.code === 200) {
            iRouter.replace("/kld/know")
          }
        })
      } else {
        addKnow(formData.form).then((data) => {
          toast(data.msg)
          console.log(data, "添加成功")
          if (data.code === 200) {
            iRouter.replace("/kld/know")
          }
        })
      }
    }
    const back = () => {
      iRouter.replace("/kld/know")
    }
    return {
      // toRefs()将响应式的对象变为普通对象 再解构，在模板中就可以直接使用属性
      ...toRefs(formData),
      formRef,
      onSubmit,
      back
    }
  }
}
</script>

<style></style>
